import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getLginPasswordStatus, getUserTree } from '@/api/system/user'
import { getExpandedKeys, deepClone, treeToArray } from '@/utils'
import { treeselect } from '@/api/system/dept'
import { encryptByKey } from '@/utils/jsencrypt'
import { ddLogin } from '@/api/dingTalk/dingTalk'
import { wxlogin } from '@/api/qywx/qywx'
import { fsLogin } from '@/api/flybook/flybook'

const user = {
  state: {
    token: getToken(),
    userId: '',
    name: '',
    loginName: '',
    avatar: '',
    tenantCode: '',
    roles: [],
    permissions: [],
    userTree: [],
    deptOption: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_LOGINNAME: (state, name) => {
      state.loginName = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USER_LIST: (state, userTree) => {
      state.userList = userTree
    },
    SET_USER_TREE: (state, userTree) => {
      state.userTree = userTree
    },
    SET_DEPT: (state, options) => {
      state.deptOption = options
    },
    SET_TENANT_CODE: (state, tenantCode) => {
      state.tenantCode = tenantCode
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = encryptByKey(userInfo.password)
      const code = userInfo.code
      const uuid = userInfo.uuid
      const verifyCode = userInfo.verifyCode
      const deviceId = userInfo.pcDeviceId
      // 多租户编号
      const tenantCode = userInfo.tenantCode
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid, tenantCode, verifyCode, deviceId).then(res => {
          if (!res.datas.token) {
            resolve(res.datas)
            return
          }
          setToken(res.datas.token)
          commit('SET_TOKEN', res.datas.token)
          commit('SET_TENANT_CODE', tenantCode)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 钉钉登录
    DdLogin({ commit }, userInfo) {
      // 多租户编号
      const tenantCode = userInfo.tenantCode
      const phonenumber = userInfo.phonenumber
      const jobId = userInfo.jobId
      return new Promise((resolve, reject) => {
        ddLogin(tenantCode, phonenumber, jobId).then(res => {
          if (!res.datas.token) {
            resolve(res.datas)
            return
          }
          setToken(res.datas.token)
          commit('SET_TOKEN', res.datas.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 企业微信登录
    WxLogin: ({ commit }, { authCode, tenantCode }) => {
      return new Promise((resolve, reject) => {
        wxlogin({ code: authCode, tenantCode }).then(res => {
          if (!res.datas.token) {
            resolve(res.datas)
            return
          }
          setToken(res.datas.token)
          commit('SET_TOKEN', res.datas.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 飞书登录
    FlyBookLogin: ({ commit }, { code, tenantCode }) => {
      return new Promise((resolve, reject) => {
        fsLogin(code, tenantCode).then(res => {
          if (!res.datas.token) {
            resolve(res.datas)
            return
          }
          setToken(res.datas.token)
          commit('SET_TOKEN', res.datas.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          if (res !== undefined && res.code === 200) {
            const user = res.datas.user
            const avatar = user.avatar
            if (res.datas.roles && res.datas.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.datas.roles)
              commit('SET_PERMISSIONS', res.datas.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_NAME', user.nickName)
            commit('SET_LOGINNAME', user.userName)
            commit('SET_USERID', user.id)
            commit('SET_AVATAR', avatar)
            resolve(res)
          } else {
            resolve(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getLoginPasswordStatus() {
      return new Promise((resolve, reject) => {
        getLginPasswordStatus().then(res => {
          if (res !== undefined && res.code === 200) {
            resolve(res)
          } else {
            resolve(res)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 获取用户列表
    async getSelTreeUser({ commit }) {
      const res = await getUserTree()
      commit('SET_USER_LIST', treeToArray(deepClone(res.data)).filter(item => item.choose))
      getExpandedKeys(res.data)
      commit('SET_USER_TREE', res.data)
    },

    // 获取部门
    async getDept({ commit }) {
      const res = await treeselect()
      commit('SET_DEPT', res.data)
    }
  }
}

export default user
